package cn.iocoder.ny.module.mall.controller.admin.product;


import cn.hutool.json.JSONException;
import cn.hutool.poi.excel.ExcelUtil;
import cn.iocoder.ny.module.mall.annotation.Decrypt;
import cn.iocoder.ny.module.mall.annotation.Encrypt;
import cn.iocoder.ny.module.mall.controller.admin.product.dto.MallProductDTO;
import cn.iocoder.ny.module.mall.controller.admin.product.dto.MallProductListDTO;
import cn.iocoder.ny.module.mall.controller.admin.product.vo.MallProductOrderVo;
import cn.iocoder.ny.module.mall.controller.admin.product.vo.MallProductPageVo;
import cn.iocoder.ny.module.mall.domain.MallConfig;
import cn.iocoder.ny.module.mall.domain.MallProduct;
import cn.iocoder.ny.module.mall.domain.MallProductSpecification;
import cn.iocoder.ny.module.mall.domain.vo.MallProductVo;
import cn.iocoder.ny.module.mall.mapper.MallProductMapper;
import cn.iocoder.ny.module.mall.service.IMallProductService;
import cn.iocoder.ny.module.mall.service.IMallProductSpecificationSerivce;
import cn.iocoder.ny.module.mall.utils.PosterUtils;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;


/**
 * @author luchunhong
 * @date 2024/08/06/ 10:33
 * @description:
 */

@RestController
@RequestMapping("product")
public class MallProductController {


    @Autowired
    private IMallProductService mallProductService;
    @Autowired
    private MallProductMapper mallProductMapper;

    @Autowired
    private IMallProductSpecificationSerivce mallProductSpecificationSerivce;
//    @Autowired
//    private QRCodeService qrCodeService;
//    @Autowired
//    private IMallQRCodeService qrCodeService;



    /**
     * 新增商品/修改商品只有操作员与商家才能进行操作
     */
//    @RequiresRoles("mall")
    @PostMapping("addProduct")
    @PreAuthorize("@ss.hasAnyRoles('merchant_admin', 'super_admin','mall_operator')")
    public CommonResult addProduct(@RequestBody @Validated({MallProduct.Add.class, MallProductSpecification.Add.class}) MallProductDTO mallProductDTO) throws JSONException, JsonProcessingException {
         mallProductService.addProduct(mallProductDTO);
//        if (!b){
//            return error(2003,"请选择最小级分类");
//        }
        return success("商品新增成功");
    }
    /**
     * 商品列表查询/分页
     */

    @PostMapping("queryProductList")
//    @Encrypt
    @PermitAll
    public CommonResult<PageResult<MallProductVo>> queryProductList(@RequestBody MallProductPageVo mallProductListDTO) {
        PageResult<MallProductVo> list = mallProductService.queryProductList(mallProductListDTO);
        return success(list);
    }
    /**
     * 根据编号查询
     * id specificationId
     */
//    @Encrypt
    @PostMapping("queryByProductId")
    public CommonResult queryByProductId(@RequestBody MallProductListDTO mallProductListDTO) {
        String bigNumberStr = String.valueOf(mallProductListDTO.getId());
        long bigNumber = Long.parseLong(bigNumberStr);
        mallProductListDTO.setId(bigNumber);
        MallProductVo mallProduct = mallProductService.queryByProductId(mallProductListDTO);
        return success(mallProduct);
    }
    /**
     * 修改商品
     */

    // 只有角色为商家以及操作员才能修改商品信息

//    @RequiresRoles("mall")
    @PostMapping("updateProductById")
    @PreAuthorize("@ss.hasAnyRoles('merchant_admin', 'super_admin','mall_operator')")
    public CommonResult updateProductById(@RequestBody @Validated({MallProduct.Edit.class, MallProductSpecification.Edit.class}) MallProductDTO mallProductDTO) {
        int i = mallProductService.updateProductById(mallProductDTO);
//        if (i == 0){
//            return error(2003,"请选择最小级分类");
//        }
        return success("修改成功");
    }

    /**
     * 查询商品列表(无分页)
     */
    @PostMapping("queryProductDropDownByTenantId")
    public CommonResult<Map<String, Object>> queryProductDropDownByTenantId() {
        List<MallProduct> mallProductVos = mallProductService.queryProductDropDownByTenantId();
        // 创建一个包含 "products" 键的结果 Map
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> productList = new ArrayList<>();
        // 将每个产品的相关信息存入列表
        for (MallProduct mallProductVo : mallProductVos) {
            Map<String, Object> productInfo = new HashMap<>();
            productInfo.put("productId", mallProductVo.getId());
            productInfo.put("title", mallProductVo.getTitle());
            productList.add(productInfo);
        }
        // 将 "products" 键和值添加到结果中
        result.put("products", productList);
        return success(result);
    }
    @PostMapping("createPoster")
    @PermitAll
    public BufferedImage createPoster() throws Exception {
        BufferedImage image = PosterUtils.createImage();
        return image;
    }



    /**
     * 该接口为软删除
     * 只有角色为商家以及操作员才能删除商品信息
     */
    @PostMapping("deleteProductById")
    @PreAuthorize("@ss.hasAnyRoles('merchant_admin', 'super_admin','mall_operator')")
    public CommonResult deleteProductById(@RequestBody MallProductDTO  mallProductDTO) {
        boolean b = mallProductService.deleteProductById(mallProductDTO);
        if (!b){
            return error(500,"删除失败");
        }
        return success("删除成功");
    }
    /**
     * 复制
     * 只有角色为商家以及操作员才能复制商品信息
     */
//    @RequiresRoles("mall")
    @PostMapping("productCopy")
    public CommonResult productCopy(@RequestBody MallProductDTO mallProductDTO) throws JSONException, JsonProcessingException {
        Integer product = mallProductService.productCopy(mallProductDTO);
        MallProductListDTO mallProductListDTO = new MallProductListDTO();
        mallProductListDTO.setId(mallProductDTO.getMallProduct().getId());
        //设置租户ID
        mallProductListDTO.setTenantId(mallProductDTO.getMallProduct().getTenantId());
        if (product == 0){
            return error(500,"请选择最小级分类");
        }
        MallProductVo mallProductVo = mallProductMapper.queryByProductId(mallProductListDTO);
        if (product == 1){
            return success(mallProductDTO);
        }
        if (product == 2){
            return success(mallProductVo);
        }
        return success(null);
    }

    /**
     * 修改库存
     * @param mallProductListDTO
     * @return
     */
    @PostMapping("upadteProductStock")
    @PreAuthorize("@ss.hasAnyRoles('merchant_admin', 'super_admin','mall_operator')")
    public CommonResult upadteProductStock(@RequestBody MallProductListDTO mallProductListDTO) {
//        String username = getLoginUser().getUsername();
//        mallProductListDTO.setUpdateBy(username);
        mallProductSpecificationSerivce.upadteProductStock(mallProductListDTO);
        return success(null);
    }



//    /**
//     * 商品批量导出Excel
//     */
//    @PostMapping("exportProduct")
//    public void exportProduct(@RequestBody MallProductListDTO mallProductListDTO, HttpServletResponse response) throws Exception {
//        List<MallProductVo> mallProducts = mallProductService.queryProductList(mallProductListDTO);
//        ExcelUtil<MallProductVo> util = new ExcelUtil<>(MallProductVo.class);
//        util.exportExcel(response, mallProducts, "商品规格");
//    }


    /**
     * 商品导入Excel
     */
//    @PostMapping("importProduct")
//    public AjaxResult importProduct(MultipartFile file) throws IOException {
//        ExcelUtil<MallProductVo> util = new ExcelUtil<MallProductVo>(MallProductVo.class);
//        List<MallProductVo> productList = util.importExcel(file.getInputStream());
//        String operName = SecurityUtils.getUsername();
//        String message = mallProductService.importProudct(productList, operName);
//        return success(message);
//    }

//    /**
//     * 导入模版下载
//     */
//    @PostMapping("/importTemplate")
//    public void importTemplate(HttpServletResponse response) throws IOException
//    {
//        ExcelUtil<MallProductExportImplents> util = new ExcelUtil<MallProductExportImplents>(MallProductExportImplents.class);
//        util.importTemplateExcel(response, "商品数据");
//    }

    /**
     * 生成二维码(商品)
     */
    @GetMapping("makeerByproductId")
    @PermitAll
    public CommonResult<String> makeerByproductId(@RequestParam String appId, @RequestParam String productId)   {
        String bytes = mallProductService.makeerByproductId(appId, productId);
        return success(bytes);
    }


    /**
     * 通过规格ID查询所需购买商品
     */
    @PostMapping("queryProductBySpecificationId")
    @PermitAll
    public CommonResult queryProductBySpecificationId(@RequestBody HashMap<String,Object> hashMap) {
        MallProductOrderVo mallProductVo = mallProductService.queryBySpecificationId(hashMap);
        return success(mallProductVo);
    }
}


